<template>
  <form-item-container
    v-if="permission !== 'H'"
    :id="id"
    :item="item"
    :item-config="itemConfig"
    @select-item="selectItem"
    @delete-item="deleteItem"
    @copy-item="copyItem"
  >
    <a-cascader
      v-if="config.options"
      v-model="formModel"
      :disabled="permission === 'D'||permission === 'R'"
      :default-value="config.defaultValue"
      :placeholder="config.placeholder"
      :allow-clear="config.allowClear"
      :allow-search="config.allowSearch"
      :path-mode="config.pathMode"
      :multiple="config.multiple"
      :max-tag-count="config.maxTagCount"
      :check-strictly="config.checkStrictly"
      :options="realOptions"
      :filter-option="filterOption"
      @change="onChange"
    />
  </form-item-container>
</template>

<script lang="ts" setup>
import { inject, defineModel, defineProps, defineEmits, computed } from 'vue';
import { FormPermission } from '@/components/form-design/item-select/config/type';
import { CascaderOption } from '@arco-design/web-vue';
import FormItemContainer from '@/components/form-design/form-container/container-item/form-item-container.vue';

const formModel = defineModel();

const props = defineProps({
  id: {
    type: String,
    default: () => ''
  },
  item: {
    type: Object,
    default: () => {
    }
  },
  itemConfig: {
    type: Object,
    default: () => {
    }
  },
  config: {
    type: Object,
    default: () => {
    }
  }
});

const formInstance = inject('formInstance');

const formPermission = inject<any>('formPermission');

const permission = computed<FormPermission>(() => {
  const result = formPermission[props.id];
  if (result) {
    return result;
  }
  return 'E';
});

const emits = defineEmits(['selectItem', 'deleteItem', 'copyItem']);

const selectItem = (value: any) => {
  emits('selectItem', props.item);
};

const deleteItem = (value: any) => {
  emits('deleteItem', props.item);
};

const copyItem = (value: any) => {
  emits('copyItem', props.item);
};

const realOptions = computed(() => {
  return JSON.parse(props.config.options);
});

const filterOption = (inputValue: string, option: CascaderOption) => {
  if (inputValue && option.label) {
    return option.label.indexOf(inputValue) !== -1;
  }
  return true;
};

const onChange = (value: string) => {
  if (props.config.onChangeFunction) {
    try {
      const callBack = new Function('value', props.config.onChangeFunction);
      callBack.call(formInstance, value);
    } catch (e) {
      console.error(e);
    }
  }
};

</script>

<script lang="ts">
export default {
  name: 'FormItemCascader'
};
</script>

<style lang="less" scoped>

</style>